// src/router/index.js
import { createRouter, createWebHashHistory } from 'vue-router'
import IndexView from '../views/IndexView.vue'
import HomeView from '../views/HomeView.vue'
import DiscoverView from '../views/DiscoverView.vue'
import { getToken, setToken, clearToken, getXauatLoginToken } from '@/utils/auth'

const routes = [
  {
    path: '/',
    name: 'index',
    component: IndexView,
    meta: { requiresAuth: true }
  },
  {
    path: '/mobiles',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/discover',
    name: 'discover',
    component: DiscoverView,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 添加重定向保护
const MAX_REDIRECTS = 3;
let redirectCount = 0;
let lastRedirectTime = 0;
let isAuthenticating = false; // 添加认证状态标志

router.beforeEach(async (to, from, next) => {
  // 修复1：同时检查URL search部分和hash部分
  const urlParams = new URLSearchParams(window.location.search);
  const hash = window.location.hash;
  const hashQueryString = hash.split('?')[1] || '';
  const hashParams = new URLSearchParams(hashQueryString);

  // 优先从URL search获取code，然后才是hash
  const code = urlParams.get('code') || hashParams.get('code');

  const token = getToken();

  console.log('路由守卫状态:', {
    currentPath: to.path,
    hasCode: !!code,  // 现在应该正确显示为true
    hasToken: !!token,
    redirectCount,
    url: window.location.href
  });

    // 1. 优先处理 code 参数（认证回调）
  if (code && !token) {
  isAuthenticating = true;
  try {
    const res = await getXauatLoginToken(code);
    if (res?.success && res.data?.accessToken) {
      setToken(res.data.accessToken);

      // 修复2：彻底清理URL中的code参数（同时清理search和hash部分）
      const cleanUrl = new URL(window.location.href);

      // 清理search部分的code
      if (cleanUrl.searchParams.has('code')) {
        cleanUrl.searchParams.delete('code');
      }

      // 清理hash部分的code
      if (cleanUrl.hash.includes('?')) {
        const [hashPath, hashQuery] = cleanUrl.hash.split('?');
        const hashParams = new URLSearchParams(hashQuery);
        if (hashParams.has('code')) {
          hashParams.delete('code');
          cleanUrl.hash = hashPath + (hashParams.toString() ? `?${hashParams.toString()}` : '');
        }
      }

      window.history.replaceState({}, document.title, cleanUrl.toString());

      console.log('认证成功，彻底清理URL并继续导航');
      window.location.href = '/';
      return;
    }
  } catch (error) {
    clearToken();
    console.error('认证失败:', error);
  } finally {
    isAuthenticating = false;
  }
}

  // 2. 检查认证状态
  if (to.matched.some(record => record.meta.requiresAuth)) {
  if (getToken()) {
    next();
  } else if (window.location.hostname === 'aimobiles.xauat.edu.cn') {
    // 修复3：在重定向前确保URL中没有code参数
    const currentUrl = new URL(window.location.href);
    const hasCodeInSearch = currentUrl.searchParams.has('code');
    const hasCodeInHash = currentUrl.hash.includes('?code=') || currentUrl.hash.includes('&code=');

    if (hasCodeInSearch || hasCodeInHash) {
      console.warn('URL中仍包含code参数，跳过重定向，等待认证处理');
      return;
    }

      // 更新重定向计数
      const now = Date.now();
      redirectCount++;
      lastRedirectTime = now;

      if (redirectCount > MAX_REDIRECTS) {
        console.warn(`重定向次数超过限制(${MAX_REDIRECTS})，等待2秒后重试`);
        redirectCount = 0;
        setTimeout(() => {
          const redirectUri = encodeURIComponent('https://aimobiles.xauat.edu.cn');
          const authUrl = `https://authserver.xauat.edu.cn/authserver/oauth2.0/authorize?response_type=code&client_id=1427671951913222144&redirect_uri=${redirectUri}`;
          window.location.href = authUrl;
        }, 2000);
        return;
      }

      // 仅当无 token 且是目标域名时重定向
      const redirectUri = encodeURIComponent('https://aimobiles.xauat.edu.cn');
      const authUrl = `https://authserver.xauat.edu.cn/authserver/oauth2.0/authorize?response_type=code&client_id=1427671951913222144&redirect_uri=${redirectUri}`;

      console.log('触发认证重定向:', authUrl);
      window.location.href = authUrl;
    } else {
      // 开发环境直接放行
      console.log('开发环境，直接放行');
      next();
    }
  } else {
    next();
  }
});

export default router
